package com.jy.api.controller.admin;

import com.jy.api.dao.*;
import com.jy.api.domain.*;
import com.jy.api.util.MyDateUtils;
import com.jy.api.vo.admin.commission.CommissionTotalVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

/**
 * Created by lihu on 2017/8/25.
 */

@RequestMapping(value = "v1/admin/", produces = "application/json;charset=utf-8")
@RestController
public class AdminCommissionController {


    private static Logger logger = LoggerFactory.getLogger(AdminCommissionController.class);

    @Autowired
    OrderDao orderDao;
    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    MemberAccountDao memberAccountDao;

    private JdbcTemplate jdbc;

    @Autowired
    private OrderItemDao itemDao;
    @Autowired
    private ProductSalesDao salesDao;
    @Autowired
    private ProductDao productDao;

    /**
     * 员工业绩统计（按月）
     *
     * @param storeId
     * @param year
     * @param month
     * @return
     */
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(method = RequestMethod.GET, value = "employee-commission")
    public ResponseEntity getStoreCommission(@RequestParam(value = "storeId", required = false) String storeId,
                                             @RequestParam(value = "year", required = false) Integer year,
                                             @RequestParam(value = "month", required = false) Integer month, @RequestParam("type") String type, @RequestParam(name = "from", required = false) String from, @RequestParam(name = "to", required = false) String to) {

        Map map1 = new HashMap();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        Date s = null;
        Date e = null;

        Map<String, Employee> employeeMap = getAllEmployeeTrue(storeId);
        try {
            if (!StringUtils.equals(type, "MONTH")) {
                year = 2018;
                month = 11;

            }
            if (year < 2017 || year > 2099 || month < 1 || month > 12) {
                return new ResponseEntity("时间参数有误,year范围（2017-2099），" +
                        "month范围（1-12）", HttpStatus.BAD_REQUEST);
            }

            ZoneId zoneId = ZoneId.of("Asia/Shanghai");
            LocalDate date = LocalDate.of(year, month, 01);
            LocalDate startDate = date.with(TemporalAdjusters.firstDayOfMonth());
            LocalDate endDate = startDate.plusMonths(1);
            ZonedDateTime startTime = startDate.atStartOfDay(zoneId);
            ZonedDateTime endTime = endDate.atStartOfDay(zoneId);
            List<Map<String, Object>> list = new ArrayList<>();
            List<CommissionTotalVo> commissionTotalVos = new LinkedList<CommissionTotalVo>();
            List<Object[]> objects = memberAccountDao.getAllTotalMemberCount(storeId, Date.from(startTime.toInstant()), Date.from(endTime.toInstant()));
            Map<String, Integer> memberMap = new HashMap<>();
            for (Object[] objects1 : objects) {
                memberMap.put(objects1[0].toString(), Integer.parseInt(objects1[1].toString()));
            }
            if (StringUtils.equals(type, "MONTH")) {
                list = orderDao.getStoreCommission(storeId,
                        Date.from(startTime.toInstant()), Date.from(endTime.toInstant()));
            } else {
                SimpleDateFormat s123 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                s123.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                list = orderDao.getStoreCommission(storeId, from, to);
            }

            BeanPropertyRowMapper<SalesTimeCommission> comMapper = new BeanPropertyRowMapper<>(SalesTimeCommission.class);
            //BeanPropertyRowMapper<Sales> kpiMapper = new BeanPropertyRowMapper<>(Sales.class);
            //kpiMapper.setPrimitivesDefaultedForNullValue(true);
            for (Map<String, Object> map : list) {
                String creatorId = map.get("creatorId").toString();
                if (StringUtils.isBlank(creatorId)) {
                    continue;
                }
                Integer orderCount = Integer.parseInt(map.get("orderCount").toString());
                Employee employee = employeeMap.get(creatorId);
                if (employee == null) {
                    continue;
                }

                SalesTimeCommission commission = new SalesTimeCommission();

                //Sales sales = new Sales();
                //SalesCommission commission = new SalesCommission();
                if (StringUtils.equals(type, "MONTH")) {
                    //sales = jdbc.queryForObject("SELECT ifnull(SUM(fs.`amount`),0) AS  amount,ifnull(SUM(fs.`qty`),0) AS qty ,ifnull(SUM(fs.`commission`),0) AS  commission FROM `f_daily_sales` fs WHERE `employee_username` =?  AND `store_id` =? AND YEAR (`biz_date`) =? AND MONTH (`biz_date`) =?"
                    //        , kpiMapper, employee.getUsername(), storeId, year, month);
                    //commission = jdbc.queryForObject("SELECT  ifnull(SUM(`qty`),0) AS qty FROM  `f_daily_sales_item`  WHERE `employee_username` =? AND commission>0 AND `store_id` =? AND YEAR (`biz_date`) =? AND MONTH (`biz_date`) =?",
                    //        comMapper, employee.getUsername(), storeId, year, month);
                    commission = jdbc.queryForObject("SELECT COUNT(id) as orderCount," +
                            "       ifnull(SUM(amount),0) as amount," +
                            "       ifnull(SUM(commission),0) as commission," +
                            "       ifnull(SUM(`count`),0) as qty" +
                            "  FROM `order`" +
                            "  WHERE `creator_id`= ?" +
                            "   and `store_id`= ?" +
                            "   and year(`payment_time`) = ?" +
                            "   and month(`payment_time`) = ?" +
                            "   and `status` IN('UNFINISHED', 'FINISHED') ", comMapper, employee.getUsername(), storeId, year, month);
                } else {
                    //sales = jdbc.queryForObject("SELECT ifnull(SUM(fs.`amount`),0) AS  amount,ifnull(SUM(fs.`qty`),0) AS qty ,ifnull(SUM(fs.`commission`),0) AS  commission FROM `f_daily_sales` fs WHERE `employee_username` =?  AND `store_id` =? AND `biz_date` >=? AND `biz_date`  <=?"
                    //        , kpiMapper, employee.getUsername(), storeId, TimeToFormateUtils.forMat(from), TimeToFormateUtils.forMat(to));
                    //commission = jdbc.queryForObject("SELECT  ifnull(SUM(`qty`),0) AS qty FROM  `f_daily_sales_item`  WHERE `employee_username` =? AND commission>0 AND `store_id` =? AND `biz_date` >=? AND `biz_date`  <=?",
                    //        comMapper, employee.getUsername(), storeId, TimeToFormateUtils.forMat(from), TimeToFormateUtils.forMat(to));
                    commission = jdbc.queryForObject("SELECT COUNT(id) as orderCount," +
                            "       ifnull(SUM(amount),0) as amount," +
                            "       ifnull(SUM(commission),0) as commission," +
                            "       ifnull(SUM(`count`),0) as qty" +
                            "  FROM `order`" +
                            " WHERE `creator_id`= ?" +
                            "   and `store_id`= ?" +
                            "   and `payment_time` BETWEEN ? and ?" +
                            "   and `status` IN('UNFINISHED', 'FINISHED') ", comMapper, employee.getUsername(), storeId, from, to);
                }

                map1 = map;
                CommissionTotalVo commissionTotalVo = new CommissionTotalVo(employee.getId(),
                        employee.getCode(), employee.getName(), employee.getGroup().getName(),
                        commission.getQty(), commission.getAmount(), commission.getCommission(), employee.getTarget(), employee.getUsername(), commission.getQty());
                if (memberMap.get(creatorId) != null) {
                    commissionTotalVo.setAddMemberNumber(memberMap.get(creatorId));
                }
                commissionTotalVos.add(commissionTotalVo);
                employeeMap.remove(creatorId);
            }
            employeeMap.forEach((key, employee) ->
                    commissionTotalVos.add(new CommissionTotalVo(employee.getId(),
                            employee.getCode(), employee.getName(), employee.getGroup().getName(), employee.getTarget()))
            );
            return new ResponseEntity(commissionTotalVos, HttpStatus.OK);
        } catch (Exception ex) {
            logger.error("getStoreCommission  is error==> storeId{},year{},month{},map1{},employeeMap:{}",
                    storeId, year, month, map1, employeeMap, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);

        }


    }

    @Autowired
    public void setJdbc(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }

    /**
     * 某员工业绩详情
     *
     * @param employeeId
     * @param storeId
     * @param year
     * @param month
     * @return
     */
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(method = RequestMethod.GET, value = "employee-commission/{employeeId}")
    public ResponseEntity getCommissionDetails(@PathVariable String employeeId,
                                               @RequestParam(value = "storeId") String storeId,
                                               @RequestParam(value = "year", required = false) int year,
                                               @RequestParam(value = "month", required = false) int month, @RequestParam("type") String type, @RequestParam(value = "from", required = false) String from, @RequestParam(value = "to", required = false) String to
    ) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
            String time = year + "-" + month;
            Date end = null;
            Date start = null;
            if (StringUtils.equals(type, "MONTH")) {
                end = MyDateUtils.getMaxMonthDate(time);
                start = MyDateUtils.getMinMonthDate(time);
            } else {
                end = simpleDateFormat.parse(to);
                start = simpleDateFormat.parse(from);
            }
            Employee employee = employeeDao.findOne(employeeId);
            BeanPropertyRowMapper itemMapper = new BeanPropertyRowMapper<>(CommissionItem.class);
            itemMapper.setPrimitivesDefaultedForNullValue(true);
            List<CommissionItem> items = null;
            items = jdbc.query("SELECT `count`AS qty,`id`AS `code`  ,`payment_time` AS paymentTime ,`commission` AS commission ,`refund_time`  as refundTime FROM `order` WHERE `creator_id` =? AND `store_id` =? AND `payment_time` >=?  AND  `payment_time` <=?  AND `enabled` =1     ORDER BY payment_time DESC ", itemMapper, employee.getUsername(), storeId, start, end);
            if (null == items) {
                items = new ArrayList<>();
            }
            List<CommissionItem> commissionItems = new ArrayList<>();
            for (CommissionItem item : items) {
                if (null==item.getRefundTime() && item.getCommission()>0){
                    commissionItems.add(item);
                }
            }
            return ResponseEntity.ok(commissionItems);
        } catch (Exception ex) {
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);

        }

    }

    /**
     * 获取店铺所有在职员工信息
     *
     * @param storeId
     * @return
     */
    private Map<String, Employee> getAllEmployeeTrue(String storeId) {
        Map<String, Employee> map = new HashMap<>();
        List<Employee> employees = employeeDao.findListByStoreIdAndEnabled(storeId, true);
        for (Employee employee : employees) {
            map.put(employee.getUsername(), employee);
        }
        return map;
    }







    @GetMapping("deal-product-call")
    public ResponseEntity dealProduct() {
        Iterable<OrderItem> list = itemDao.findAll();
        for (OrderItem item : list) {
            if (!item.getProductName().contains("网费") &&!item.getProductName().contains("充值")) {
                ProductSales productSales = salesDao.findByProductId(item.getProductId());
                if (productSales != null) {
                    productSales.setCount(productSales.getCount() + item.getQuantity());
                } else {
                    Product product = productDao.findOne(item.getProductId());
                    productSales = new ProductSales();
                    productSales.setProductId(item.getProductId());
                    productSales.setStoreId(product.getStoreId());
                    productSales.setProductName(product.getName());
                    productSales.setCount(item.getQuantity());
                }
                salesDao.save(productSales);
            }
        }
        return ResponseEntity.ok("处理成功");
    }


}
